package com.lyn.pluginbazaar.utils;

import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public class CheckUtil {

    public static String check(Object object) {
        if (object == null) {
            return "请求参数不能为空";
        }
        Class<?> aClass = object.getClass();
        java.lang.reflect.Field[] declaredFields = aClass.getDeclaredFields();
        for (java.lang.reflect.Field field : declaredFields) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(NotNull.class)) {
                NotNull checkNotNull = field.getAnnotation(NotNull.class);
                Object o = null;
                try {
                    o = field.get(object);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (StringUtils.isEmpty(o)) {
                    return field.getName() + checkNotNull.msg();
                }
            }
            if (field.isAnnotationPresent(Length.class)) {
                Length length = field.getAnnotation(Length.class);
                Object o = null;
                try {
                    o = field.get(object);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                String value = (String) o;
                if (value.length() < length.length()) {
                    return length.msg();
                }
            }
        }
        return null;
    }

    public static boolean isEmpty(@Nullable Object str) {
        return str == null || "".equals(str);
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD})
    public @interface NotNull {
        String msg() default "不能为空!";

    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD})
    public @interface Length {
        int length() default 0;
        String msg() default "";

    }
}
